package com.interceptor;

import com.bean.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author 末日流光
 * @ClASSNAME LoginInterceptor
 * @PACKAGE_NAME com.interceptor
 * @date 2022/5/12 22:39
 * @project SSM-demo1
 * @company dzy
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session=request.getSession();
        User user=(User)session.getAttribute("adminUser");
        if (user==null){
            String basepath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().print("<script>alert('你无权访问该页面，请登录！');</script>");
            response.setHeader("refresh", "0.1;url="+basepath);
            return false;
        }else{
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }
}

